/**
 * 
 */
package com.surekam.mnai.service.extractor.parser;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.surekam.mnai.model.Address;
import com.surekam.mnai.model.MobileNumberAttribution;
import com.surekam.mnai.util.StringUtil;

/**
 * 中国移动HTTP协议端口返回的归属信息的解析器。
 * 
 * @author 吴政
 * 
 */
public class CMCCParser implements IMobileNumberAttributionParser {

	// @Autowired
	// private IAddressService addressService;

	/**
	 * @see com.surekam.mnai.service.extractor.parser.IMobileNumberAttributionParser#parse(java.io.InputStream)
	 */
	@Override
	public MobileNumberAttribution parse(InputStream is)
			throws ParseFailedException {
		return createMobileNumberAttribution(readProperties(is));
	}

	private Map<String, String> readProperties(InputStream is)
			throws ParseFailedException {
		byte[] buf = new byte[100];
		BufferedInputStream input = new BufferedInputStream(is);
		String result = "";

		try {
			int length = input.read(buf);

			result = new String(buf, 0, length, "GBK");
		} catch (IOException e) {
			throw new ParseFailedException(e);
		}

		String[] properties = result.split("&");

		validateProperties(properties);

		Map<String, String> propertyMap = new HashMap<String, String>();

		propertyMap.put("mobileNumberSegment", properties[0].substring(0, 7));
		propertyMap.put(
				"province",
				(properties[1].endsWith("省") ? properties[1].substring(0,
						properties[1].length() - 1) : properties[1]));
		propertyMap.put(
				"city",
				(properties[2].endsWith("市") ? properties[2].substring(0,
						properties[2].length() - 1) : properties[2]));
		propertyMap.put("areaCode", properties[3]);

		return propertyMap;
	}

	/**
	 * 验证返回的结果属性数组是否正确。
	 * 
	 * @param properties
	 *            结果的属性数组
	 * @throws ParseFailedException
	 *             如果结果属性数组数据不正确，则抛出此异常。
	 */
	private void validateProperties(String[] properties)
			throws ParseFailedException {
		if (properties.length != 4 || StringUtil.isEmpty(properties[0])
				|| StringUtil.isEmpty(properties[1])
				|| StringUtil.isEmpty(properties[2])
				|| StringUtil.isEmpty(properties[3])) {
			throw new ParseFailedException("Wrong result.");
		}
	}

	private MobileNumberAttribution createMobileNumberAttribution(
			Map<String, String> propertyMap) {
		Address address = createAddress(propertyMap);

		return new MobileNumberAttribution(
				propertyMap.get("mobileNumberSegment"), "", address, new Date());
	}

	private Address createAddress(Map<String, String> propertyMap) {
		return new Address(0, propertyMap.get("province"),
				propertyMap.get("city"), propertyMap.get("areaCode"), "");
		// return addressService.loadByProvinceAndCity(province, city);
	}

}
